import React, { useState } from 'react'
import useDialogState from '@/hooks/use-dialog-state'
import { type Table } from '../data/schema'

type TablesDialogType = 'invite' | 'add' | 'edit' | 'delete'

interface TablesContextType {
  open: TablesDialogType | null
  setOpen: (str: TablesDialogType | null) => void
  currentRow: Table | null
  setCurrentRow: React.Dispatch<React.SetStateAction<Table | null>>
}

const TablesContext = React.createContext<TablesContextType | null>(null)

interface Props {
  children: React.ReactNode
}

export default function TablesProvider({ children }: Props) {
  const [open, setOpen] = useDialogState<TablesDialogType>(null)
  const [currentRow, setCurrentRow] = useState<Table | null>(null)

  return (
    <TablesContext value={{ open, setOpen, currentRow, setCurrentRow }}>
      {children}
    </TablesContext>
  )
}

// eslint-disable-next-line react-refresh/only-export-components
export const useTables = () => {
  const adminsContext = React.useContext(TablesContext)

  if (!adminsContext) {
    throw new Error('useTables has to be used within <TablesContext>')
  }

  return adminsContext
}
